package tech.cn.note.word;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.hutool.core.util.StrUtil;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.policy.AbstractRenderPolicy;
import com.deepoove.poi.render.RenderContext;
import com.deepoove.poi.render.compute.RenderDataCompute;
import com.deepoove.poi.template.ElementTemplate;
import com.deepoove.poi.template.run.RunTemplate;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import tech.cn.note.utils.CheckUtil;
import tech.cn.note.word.fun.RenderFunction;

public class StrongRenderPolicy extends AbstractRenderPolicy<Object> {

    /**
     * 获取${%( 中间的函数字符串
     */
    private static final Pattern PATTERN = Pattern.compile("\\$\\{\\%(.*?)\\((.*)\\)");

    private Map<String, RenderFunction> functionMap;

    public StrongRenderPolicy(Map<String, RenderFunction> functionMap) {
        this.functionMap = functionMap;
    }

    @Override
    public void render(ElementTemplate eleTemplate, Object data, XWPFTemplate template) {
        RenderDataCompute renderDataCompute = template.getConfig().getRenderDataComputeFactory().newCompute(PoiTemplateDataFillServiceImpl.threadLocal.get());
        XWPFRun run = ((RunTemplate) eleTemplate).getRun();
        String placeHolder = run.toString();
        logger.debug("placeHolder is {}", placeHolder);
        if (StringUtils.isBlank(placeHolder)) {
            run.setText(StrUtil.EMPTY, 0);
            return;
        }
        String functionStr;
        // 现在创建 matcher 对象
        Matcher matcher = PATTERN.matcher(placeHolder);
        if (matcher.find()) {
            functionStr = matcher.group(1);
        } else {
            throw new RuntimeException("[" + placeHolder + "]表达式不符合规则,请按照${%function(var,var2,var3)}格式");
        }
        RenderFunction renderFunction = functionMap.get(functionStr);
        if (renderFunction == null) {
            throw new RuntimeException(String.format("不支持的函数%s", functionStr));
        }

        String vars = matcher.group(2);
        CheckUtil.checkExpression(StringUtils.isNotEmpty(vars), "表达式不符合规则,请按照${%function(var,var2,var3)}格式");
        String result = renderFunction.doCalculate(vars.split(","), renderDataCompute);
        if (result == null || StrUtil.NULL.equals(result)) {
            run.setText("", 0);
            return;
        }
        run.setText(result, 0);
    }

    @Override
    public void doRender(RenderContext<Object> context) {

    }

    @Override
    protected void afterRender(RenderContext<Object> context) {
        // 清空标签
        clearPlaceholder(context, true);
    }

    @Override
    protected void beforeRender(RenderContext<Object> context) {
        // 清空标签
        clearPlaceholder(context, true);
    }
}